const axios = require("axios");
const assert = require("assert");

// 测试配置
const BASE_URL = "http://localhost:3001";
const USER_TOKEN = "eyJhbGciOiJIUzI1NiIsInR5cCI6IkpXVCJ9.eyJ1c2VybmFtZSI6InRlc3R1c2VyIiwidXNlcmlkIjoidGVzdF91c2VyXzEyMyIsImlhdCI6MTcwMDAwMDAwMCwiZXhwIjoxODAwMDAwMDAwfQ.fake_signature"; // 测试用token

// 创建axios实例
const api = axios.create({
  baseURL: BASE_URL,
  headers: {
    "Content-Type": "application/json",
    token: USER_TOKEN,
  },
});

// 测试数据
let testData = {
  userid: "test_user_123",
  testOrderId: null,
  testTime: null,
};

/**
 * 测试订单列表接口
 */
async function testOrderListAPI() {
  console.log("\n=== 测试订单列表接口 GET /api/order/list ===");

  try {
    // 1. 测试基本订单列表获取
    console.log("1. 测试基本订单列表获取...");
    const listResponse = await api.get("/api/order/list", {
      params: {
        userid: testData.userid,
        page: 1,
        pageSize: 10
      },
    });
    
    // 验证响应结构
    assert.strictEqual(listResponse.data.code, "200");
    assert.strictEqual(listResponse.data.message, "获取订单列表成功");
    assert(listResponse.data.data, "应该返回data字段");
    assert(Array.isArray(listResponse.data.data.list), "应该返回订单列表数组");
    assert(typeof listResponse.data.data.total === "number", "应该返回总数");
    assert(typeof listResponse.data.data.page === "number", "应该返回页码");
    assert(typeof listResponse.data.data.pageSize === "number", "应该返回页大小");
    
    console.log("✓ 订单列表获取成功");
    console.log(`  - 总订单数: ${listResponse.data.data.total}`);
    console.log(`  - 当前页订单数: ${listResponse.data.data.list.length}`);
    console.log(`  - 页码: ${listResponse.data.data.page}`);
    console.log(`  - 页大小: ${listResponse.data.data.pageSize}`);

    // 2. 测试状态筛选
    console.log("2. 测试状态筛选...");
    const statusFilterResponse = await api.get("/api/order/list", {
      params: {
        userid: testData.userid,
        status: 0, // 未支付状态
        page: 1,
        pageSize: 5
      },
    });
    
    assert.strictEqual(statusFilterResponse.data.code, "200");
    console.log(`✓ 状态筛选成功，未支付订单数: ${statusFilterResponse.data.data.total}`);

    // 3. 测试分页
    console.log("3. 测试分页功能...");
    const paginationResponse = await api.get("/api/order/list", {
      params: {
        userid: testData.userid,
        page: 2,
        pageSize: 3
      },
    });
    
    assert.strictEqual(paginationResponse.data.code, "200");
    assert.strictEqual(paginationResponse.data.data.page, 2);
    assert.strictEqual(paginationResponse.data.data.pageSize, 3);
    console.log(`✓ 分页功能正常，第2页订单数: ${paginationResponse.data.data.list.length}`);

    // 保存测试数据
    if (listResponse.data.data.list.length > 0) {
      testData.testOrderId = listResponse.data.data.list[0].orderid;
      testData.testTime = listResponse.data.data.list[0].time;
      console.log(`  - 保存测试订单ID: ${testData.testOrderId}`);
      console.log(`  - 保存测试时间: ${testData.testTime}`);
    }

    console.log("✅ 订单列表接口测试通过");
  } catch (error) {
    console.error(
      "❌ 订单列表接口测试失败:",
      error.response?.data || error.message
    );
    throw error;
  }
}

/**
 * 测试订单详情接口
 */
async function testOrderDetailAPI() {
  console.log("\n=== 测试订单详情接口 GET /api/order/detail/:orderid ===");

  try {
    if (!testData.testOrderId) {
      console.log("⚠️ 没有可用的测试订单ID，跳过详情测试");
      return;
    }

    // 1. 测试获取订单详情
    console.log("1. 测试获取订单详情...");
    const detailResponse = await api.get(`/api/order/detail/${testData.testOrderId}`, {
      params: {
        userid: testData.userid
      },
    });
    
    // 验证响应结构
    assert.strictEqual(detailResponse.data.code, "200");
    assert.strictEqual(detailResponse.data.message, "获取订单详情成功");
    assert(detailResponse.data.data, "应该返回data字段");
    assert(detailResponse.data.data.orderInfo, "应该返回订单基本信息");
    assert(Array.isArray(detailResponse.data.data.items), "应该返回订单商品列表");
    assert(typeof detailResponse.data.data.totalAmount === "number", "应该返回总金额");
    
    console.log("✓ 订单详情获取成功");
    console.log(`  - 订单ID: ${detailResponse.data.data.orderInfo.orderid}`);
    console.log(`  - 订单状态: ${detailResponse.data.data.orderInfo.status}`);
    console.log(`  - 商品数量: ${detailResponse.data.data.items.length}`);
    console.log(`  - 总金额: ${detailResponse.data.data.totalAmount}`);
    console.log(`  - 收货人: ${detailResponse.data.data.orderInfo.name || '未设置'}`);
    console.log(`  - 收货电话: ${detailResponse.data.data.orderInfo.tel || '未设置'}`);

    // 2. 测试不存在的订单
    console.log("2. 测试不存在的订单...");
    try {
      await api.get("/api/order/detail/nonexistent_order_id", {
        params: {
          userid: testData.userid
        },
      });
      console.log("⚠️ 应该返回404，但请求成功了");
    } catch (error) {
      if (error.response?.status === 404 || error.response?.data?.code === "404") {
        console.log("✓ 正确处理了不存在的订单");
      } else {
        console.log("✓ 服务器处理了不存在的订单请求");
      }
    }

    console.log("✅ 订单详情接口测试通过");
  } catch (error) {
    console.error(
      "❌ 订单详情接口测试失败:",
      error.response?.data || error.message
    );
    throw error;
  }
}

/**
 * 测试订单搜索接口
 */
async function testOrderSearchAPI() {
  console.log("\n=== 测试订单搜索接口 GET /api/order/search ===");

  try {
    // 1. 测试基本搜索功能
    console.log("1. 测试基本搜索功能...");
    const searchResponse = await api.get("/api/order/search", {
      params: {
        userid: testData.userid,
        keyword: "order", // 搜索包含order的订单
        page: 1,
        pageSize: 10
      },
    });
    
    // 验证响应结构
    assert.strictEqual(searchResponse.data.code, "200");
    assert.strictEqual(searchResponse.data.message, "搜索订单成功");
    assert(searchResponse.data.data, "应该返回data字段");
    assert(Array.isArray(searchResponse.data.data.list), "应该返回搜索结果列表");
    assert(typeof searchResponse.data.data.total === "number", "应该返回总数");
    assert(searchResponse.data.data.keyword === "order", "应该返回搜索关键词");
    
    console.log("✓ 订单搜索成功");
    console.log(`  - 搜索关键词: ${searchResponse.data.data.keyword}`);
    console.log(`  - 搜索结果数: ${searchResponse.data.data.total}`);
    console.log(`  - 当前页结果数: ${searchResponse.data.data.list.length}`);

    // 2. 测试空关键词搜索
    console.log("2. 测试空关键词搜索...");
    const emptySearchResponse = await api.get("/api/order/search", {
      params: {
        userid: testData.userid,
        keyword: "",
        page: 1,
        pageSize: 5
      },
    });
    
    assert.strictEqual(emptySearchResponse.data.code, "200");
    console.log(`✓ 空关键词搜索成功，返回所有订单数: ${emptySearchResponse.data.data.total}`);

    // 3. 测试结合状态筛选的搜索
    console.log("3. 测试结合状态筛选的搜索...");
    const statusSearchResponse = await api.get("/api/order/search", {
      params: {
        userid: testData.userid,
        keyword: "test",
        status: 0, // 未支付状态
        page: 1,
        pageSize: 5
      },
    });
    
    assert.strictEqual(statusSearchResponse.data.code, "200");
    console.log(`✓ 状态筛选搜索成功，结果数: ${statusSearchResponse.data.data.total}`);

    console.log("✅ 订单搜索接口测试通过");
  } catch (error) {
    console.error(
      "❌ 订单搜索接口测试失败:",
      error.response?.data || error.message
    );
    throw error;
  }
}

/**
 * 测试订单统计接口
 */
async function testOrderStatisticsAPI() {
  console.log("\n=== 测试订单统计接口 GET /api/order/statistics ===");

  try {
    // 1. 测试获取订单统计信息
    console.log("1. 测试获取订单统计信息...");
    const statisticsResponse = await api.get("/api/order/statistics", {
      params: {
        userid: testData.userid
      },
    });
    
    // 验证响应结构
    assert.strictEqual(statisticsResponse.data.code, "200");
    assert.strictEqual(statisticsResponse.data.message, "获取订单统计成功");
    assert(statisticsResponse.data.data, "应该返回data字段");
    assert(typeof statisticsResponse.data.data.totalOrders === "number", "应该返回总订单数");
    assert(typeof statisticsResponse.data.data.totalAmount === "number", "应该返回总金额");
    assert(statisticsResponse.data.data.statusCount, "应该返回状态统计");
    assert(Array.isArray(statisticsResponse.data.data.recentOrders), "应该返回最近订单列表");
    
    console.log("✓ 订单统计信息获取成功");
    console.log(`  - 总订单数: ${statisticsResponse.data.data.totalOrders}`);
    console.log(`  - 总金额: ${statisticsResponse.data.data.totalAmount}`);
    console.log(`  - 未支付订单: ${statisticsResponse.data.data.statusCount.unpaid}`);
    console.log(`  - 待发货订单: ${statisticsResponse.data.data.statusCount.pending_shipment}`);
    console.log(`  - 待收货订单: ${statisticsResponse.data.data.statusCount.pending_delivery}`);
    console.log(`  - 待评价订单: ${statisticsResponse.data.data.statusCount.pending_review}`);
    console.log(`  - 已完成订单: ${statisticsResponse.data.data.statusCount.completed}`);
    console.log(`  - 最近订单数: ${statisticsResponse.data.data.recentOrders.length}`);

    console.log("✅ 订单统计接口测试通过");
  } catch (error) {
    console.error(
      "❌ 订单统计接口测试失败:",
      error.response?.data || error.message
    );
    throw error;
  }
}

/**
 * 测试订单状态统计接口
 */
async function testOrderStatusCountAPI() {
  console.log("\n=== 测试订单状态统计接口 GET /api/order/statusCount ===");

  try {
    // 1. 测试获取状态统计
    console.log("1. 测试获取状态统计...");
    const statusCountResponse = await api.get("/api/order/statusCount", {
      params: {
        userid: testData.userid
      },
    });
    
    // 验证响应结构
    assert.strictEqual(statusCountResponse.data.code, "200");
    assert.strictEqual(statusCountResponse.data.message, "获取状态统计成功");
    assert(statusCountResponse.data.data, "应该返回data字段");
    assert(typeof statusCountResponse.data.data[0] === "number", "应该返回未支付数量");
    assert(typeof statusCountResponse.data.data[1] === "number", "应该返回待发货数量");
    assert(typeof statusCountResponse.data.data[2] === "number", "应该返回待收货数量");
    assert(typeof statusCountResponse.data.data[3] === "number", "应该返回待评价数量");
    assert(typeof statusCountResponse.data.data[4] === "number", "应该返回已完成数量");
    assert(typeof statusCountResponse.data.data.total === "number", "应该返回总数");
    
    console.log("✓ 状态统计获取成功");
    console.log(`  - 未支付(0): ${statusCountResponse.data.data[0]}`);
    console.log(`  - 待发货(1): ${statusCountResponse.data.data[1]}`);
    console.log(`  - 待收货(2): ${statusCountResponse.data.data[2]}`);
    console.log(`  - 待评价(3): ${statusCountResponse.data.data[3]}`);
    console.log(`  - 已完成(4): ${statusCountResponse.data.data[4]}`);
    console.log(`  - 总计: ${statusCountResponse.data.data.total}`);

    console.log("✅ 订单状态统计接口测试通过");
  } catch (error) {
    console.error(
      "❌ 订单状态统计接口测试失败:",
      error.response?.data || error.message
    );
    throw error;
  }
}

/**
 * 测试订单状态操作接口
 */
async function testOrderStatusOperationsAPI() {
  console.log("\n=== 测试订单状态操作接口 ===");

  try {
    if (!testData.testOrderId) {
      console.log("⚠️ 没有可用的测试订单ID，跳过状态操作测试");
      return;
    }

    // 1. 测试更新订单状态
    console.log("1. 测试更新订单状态 POST /api/order/updateStatus...");
    try {
      const updateStatusResponse = await api.post("/api/order/updateStatus", {
        orderid: testData.testOrderId,
        userid: testData.userid,
        status: 1 // 尝试更新为待发货
      });
      
      if (updateStatusResponse.data.code === "200") {
        console.log(`✓ 状态更新成功: ${updateStatusResponse.data.message}`);
      } else {
        console.log(`⚠️ 状态更新响应: ${updateStatusResponse.data.message}`);
      }
    } catch (error) {
      console.log(`⚠️ 状态更新请求处理: ${error.response?.data?.message || error.message}`);
    }

    // 2. 测试取消订单
    console.log("2. 测试取消订单 POST /api/order/cancel...");
    try {
      const cancelResponse = await api.post("/api/order/cancel", {
        orderid: testData.testOrderId,
        userid: testData.userid,
        reason: "测试取消"
      });
      
      if (cancelResponse.data.code === "200") {
        console.log(`✓ 订单取消成功: ${cancelResponse.data.message}`);
      } else {
        console.log(`⚠️ 订单取消响应: ${cancelResponse.data.message}`);
      }
    } catch (error) {
      console.log(`⚠️ 订单取消请求处理: ${error.response?.data?.message || error.message}`);
    }

    // 3. 测试确认收货
    console.log("3. 测试确认收货 POST /api/order/confirm...");
    try {
      const confirmResponse = await api.post("/api/order/confirm", {
        orderid: testData.testOrderId,
        userid: testData.userid
      });
      
      if (confirmResponse.data.code === "200") {
        console.log(`✓ 确认收货成功: ${confirmResponse.data.message}`);
      } else {
        console.log(`⚠️ 确认收货响应: ${confirmResponse.data.message}`);
      }
    } catch (error) {
      console.log(`⚠️ 确认收货请求处理: ${error.response?.data?.message || error.message}`);
    }

    console.log("✅ 订单状态操作接口测试完成");
  } catch (error) {
    console.error(
      "❌ 订单状态操作接口测试失败:",
      error.response?.data || error.message
    );
    // 不抛出错误，因为状态操作可能因为业务逻辑限制而失败
  }
}

/**
 * 验证数据一致性
 */
async function verifyDataConsistency() {
  console.log("\n=== 验证接口间数据一致性 ===");

  try {
    // 获取订单列表和统计信息，验证数据一致性
    const [listResponse, statisticsResponse, statusCountResponse] = await Promise.all([
      api.get("/api/order/list", {
        params: { userid: testData.userid, page: 1, pageSize: 100 }
      }),
      api.get("/api/order/statistics", {
        params: { userid: testData.userid }
      }),
      api.get("/api/order/statusCount", {
        params: { userid: testData.userid }
      })
    ]);

    const listTotal = listResponse.data.data.total;
    const statisticsTotal = statisticsResponse.data.data.totalOrders;
    const statusCountTotal = statusCountResponse.data.data.total;

    console.log("1. 验证订单总数一致性...");
    console.log(`  - 列表接口总数: ${listTotal}`);
    console.log(`  - 统计接口总数: ${statisticsTotal}`);
    console.log(`  - 状态统计总数: ${statusCountTotal}`);

    if (listTotal === statisticsTotal && statisticsTotal === statusCountTotal) {
      console.log("✓ 订单总数一致性验证通过");
    } else {
      console.log("⚠️ 订单总数存在不一致，可能是正常的业务逻辑差异");
    }

    console.log("2. 验证状态统计一致性...");
    const statisticsStatusCount = statisticsResponse.data.data.statusCount;
    const statusCountData = statusCountResponse.data.data;
    
    console.log(`  - 统计接口未支付: ${statisticsStatusCount.unpaid}`);
    console.log(`  - 状态统计未支付: ${statusCountData[0]}`);
    
    if (statisticsStatusCount.unpaid === statusCountData[0]) {
      console.log("✓ 未支付状态统计一致");
    } else {
      console.log("⚠️ 未支付状态统计存在差异");
    }

    console.log("✅ 数据一致性验证完成");
  } catch (error) {
    console.error(
      "❌ 数据一致性验证失败:",
      error.response?.data || error.message
    );
    // 不抛出错误，因为这是验证性测试
  }
}

/**
 * 检查服务器状态
 */
async function checkServerStatus() {
  console.log("\n=== 检查服务器状态 ===");
  
  try {
    const response = await axios.get(`${BASE_URL}/api/order/statusCount?userid=${testData.userid}`, {
      headers: { token: USER_TOKEN },
      timeout: 5000
    });
    
    if (response.status === 200) {
      console.log("✓ 服务器运行正常");
      console.log(`  - 服务器地址: ${BASE_URL}`);
      console.log(`  - 响应时间: ${response.headers['x-response-time'] || '未知'}`);
      return true;
    }
  } catch (error) {
    console.error("❌ 服务器连接失败:", error.message);
    console.error("请确保服务器正在运行在 http://localhost:3001");
    return false;
  }
}

// 添加延迟函数
function delay(ms) {
  return new Promise(resolve => setTimeout(resolve, ms));
}

/**
 * 主测试函数
 */
async function runAllTests() {
  console.log("🚀 开始订单接口数据获取测试");
  console.log("测试目标：验证新增订单接口的数据获取功能");
  console.log("请确保：");
  console.log("1. 服务器正在运行 (http://localhost:3001)");
  console.log("2. 已设置正确的用户token");
  console.log("3. 数据库连接正常");
  console.log("4. 数据库中存在测试用户的订单数据");

  try {
    // 检查服务器状态
    const serverOk = await checkServerStatus();
    if (!serverOk) {
      console.log("\n💥 服务器连接失败，测试终止");
      process.exit(1);
    }
    
    await delay(1000);

    // 执行各项测试
    await testOrderListAPI();
    await delay(1000);
    
    await testOrderDetailAPI();
    await delay(1000);
    
    await testOrderSearchAPI();
    await delay(1000);
    
    await testOrderStatisticsAPI();
    await delay(1000);
    
    await testOrderStatusCountAPI();
    await delay(1000);
    
    await testOrderStatusOperationsAPI();
    await delay(1000);
    
    await verifyDataConsistency();

    console.log("\n🎉 所有订单接口数据获取测试完成！");
    console.log("\n📊 测试总结：");
    console.log("✅ 订单列表接口 - 数据获取正常");
    console.log("✅ 订单详情接口 - 数据获取正常");
    console.log("✅ 订单搜索接口 - 数据获取正常");
    console.log("✅ 订单统计接口 - 数据获取正常");
    console.log("✅ 状态统计接口 - 数据获取正常");
    console.log("✅ 状态操作接口 - 功能测试完成");
    console.log("✅ 数据一致性验证 - 完成");
    
  } catch (error) {
    console.error("\n💥 测试过程中出现错误:", error.message);
    console.error("详细错误信息:", error.response?.data || error.stack);
    process.exit(1);
  }
}

// 运行测试
if (require.main === module) {
  runAllTests();
}

module.exports = {
  runAllTests,
  testOrderListAPI,
  testOrderDetailAPI,
  testOrderSearchAPI,
  testOrderStatisticsAPI,
  testOrderStatusCountAPI,
  testOrderStatusOperationsAPI,
  verifyDataConsistency,
  checkServerStatus
};